#ifndef _THREAD_SAFE_MESSAGE_QUEUE_H
#define _THREAD_SAFE_MESSAGE_QUEUE_H

namespace Utilities
{
	template <class T>
	struct MessageContainer
	{
		T message;
		MessageContainer* next;

		MessageContainer()
		{
			next = NULL;
		}
	};

	template <class T>
	class ThreadSafeQueue
	{
	public:
		ThreadSafeQueue();
		~ThreadSafeQueue();

		const bool Dequeue(T& aMessage);
		void Enqueue(const T& aMessage);

		MessageContainer<T> *First() { return myFirstMessage; }
		MessageContainer<T> *Last() { return myLastMessage; }

		const bool IsEmpty() const;

	private:
		MessageContainer<T>* myFirstMessage;
		MessageContainer<T>* myLastMessage;

	};

	template <class T>
	ThreadSafeQueue<T>::ThreadSafeQueue()
	{
		myLastMessage = myFirstMessage = new MessageContainer<T>();
	}

	template <class T>
	ThreadSafeQueue<T>::~ThreadSafeQueue()
	{
		while( myFirstMessage->next )
		{
			MessageContainer<T> *temp = myFirstMessage;
			myFirstMessage = myFirstMessage->next;
			delete( temp );
		}

		delete( myFirstMessage );
	}

	template <class T>
	const bool ThreadSafeQueue<T>::Dequeue(T& aMessage)
	{
		if( myFirstMessage->next != NULL )
		{
			aMessage = myFirstMessage->message;
			MessageContainer<T> *tempMessage = myFirstMessage;
			myFirstMessage = myFirstMessage->next;
			delete( tempMessage );

			return true;
		}

		return false;
	}

	template <class T>
	void ThreadSafeQueue<T>::Enqueue(const T& aMessage)
	{
		myLastMessage->message = aMessage;
		MessageContainer<T> *tempMessage = new MessageContainer<T>();
		myLastMessage->next = tempMessage;
		myLastMessage = tempMessage;
	}


	template <class T>
	const bool ThreadSafeQueue<T>::IsEmpty() const
	{
		return myFirstMessage == myLastMessage;
	}
}

#endif


